from flask import session, current_app, g

from info.models import User
import functools


# 自定义过滤器
def func_index_convert(value):
    convert_dict = {
        1: "first",
        2: "second",
        3: "third"
    }
    return convert_dict.get(value, None)


def user_login_data(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 判断用户是否登陆     可以通过session中的数据判断用户是否登陆
        # 从session中取出用户主键
        user_id = session.get('user_id')
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)

        g.user = user
        return f(*args, **kwargs)

    return wrapper


# 文件上传
def file_upload(data):
    """
    文件上传
    :param data: 上传的内容
    :return: 文件名
    """
    import qiniu
    access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
    secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
    bucket_name = "infonews"

    q = qiniu.Auth(access_key, secret_key)
    key = None  # 设置文件名, 设置None会生成随机名称
    token = q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key, data)

    if ret is not None:  # 上传成功, 返回文件名

        return ret.get("key")  # 获取随机文件名

    else:  # 上传失败
        raise BaseException(info)
